package com.authine.cloudpivot.web.api.excel;

import com.authine.cloudpivot.utils.JxlsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Api(description = "打印接口", tags = "打印接口")
@RestController
@RequestMapping(value = "/api/download")
@CrossOrigin
public class PrintController {
    private static final Logger log = LoggerFactory.getLogger(PrintController.class);

    @Value("${cloudpivot.print.template.path}")
    private String templatePath;

    @ApiOperation(value = "打印")
    @RequestMapping(value = "/downloadExcel", method = RequestMethod.POST)
    @CrossOrigin
    public void excel(HttpServletResponse response, @RequestBody Map<String, Object> map) {
        Map<String, Object> map1=(Map<String, Object>)map.get("data");
        Map<String, Object> map2 = (Map<String, Object>)map1.get("bizObject");
        Map<String, Object> map3 = (HashMap<String, Object>)map2.get("data");

        String templateName = (String) map.get("templateName");
        templateName = StringUtils.isBlank(templateName) ? "apply.xlsx" : templateName;
        try {
            templatePath = StringUtils.isBlank(templatePath) ? ResourceUtils.getURL("classpath:").getPath() + "templates" : templatePath;
            String templatePathFull = templatePath + "/" + templateName;
            log.info("===>> Start download excel,templatePathFull = {}", templatePathFull);

            OutputStream out = null;
            templateName = new String(templateName.getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", templateName));

            response.setCharacterEncoding("UTF-8");
            //调用封装的工具类，传入模板路径，输出流，和装有数据的Map,按照模板导出
            out = response.getOutputStream();
            JxlsUtils.exportExcel(templatePathFull, out, map3);
            out.close();
            log.info("===>> end download excel.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
